import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import pandas as pd
import warnings
import tkinter as tk
import PySimpleGUI as sg
from tkinter import messagebox
# import requests

root = tk.Tk()
root.withdraw()

plt.rcParams['font.family'] = 'SimHei'
warnings.filterwarnings('ignore')
window = sg.Window(title='fjsafj')

def month_analyze(sth, s_g, file_path='情感词分析.csv'):
    data = pd.read_csv(file_path, encoding='utf-8')
    Specify_data = data[data['itemName'] == sth]
    Specify_data['commentTime'] = pd.to_datetime(Specify_data['commentTime'])
    Specify_data['Month'] = Specify_data['commentTime'].dt.month
    Specify_data['Day'] = Specify_data['commentTime'].dt.day

    # 定义调色板
    palette = {'正面': (67 / 255, 255 / 255, 183 / 255), '中性': (255 / 255, 206 / 255, 70 / 255),
               '负面': (158 / 255, 41 / 255, 39 / 255)}

    fig = sns.catplot(x='Day', hue='Sentiment', col='Month', data=Specify_data, kind='count', palette=palette,
                      alpha=0.7, height=6, aspect=1.2)
    fig.set_axis_labels('Day', 'Comment Count')
    fig.set_xticklabels(rotation=45)
    # plt.ylim(0, 70)  # 取固定评论数量（自定义）
    # 预警功能
    x = Specify_data['Day'].unique()

    good_counts = Specify_data[Specify_data['Sentiment'] == '正面']['Day'].value_counts()
    neutral_counts = Specify_data[Specify_data['Sentiment'] == '中性']['Day'].value_counts()
    bad_counts = Specify_data[Specify_data['Sentiment'] == '负面']['Day'].value_counts()

    # 添加缺失日期的代码
    for day in range(1, 32):  # 修改范围以适应实际日期范围
        if day not in good_counts:
            good_counts[day] = 0
        if day not in neutral_counts:
            neutral_counts[day] = 0
        if day not in bad_counts:
            bad_counts[day] = 0

    for i in range(1, len(x)):
        if i > 0 and good_counts[x[i - 1]] > 0 and bad_counts[x[i - 1]] > 0 \
                and ((good_counts[x[i - 1]] < bad_counts[x[i - 1]] * 1.1
                     or good_counts[x[i - 1]] < (bad_counts[x[i - 1]] + neutral_counts[x[i - 1]]) * 0.5)):

            max_height = max(good_counts[x[i - 1]], bad_counts[x[i - 1]], neutral_counts[x[i - 1]])
            plt.annotate('Warning!', (x[i], max_height), ha='center', va='bottom',
                         xytext=(0, 10), textcoords='offset points',
                         color=(169 / 255, 72 / 255, 41 / 255),
                         alpha=1, fontsize=12)
            # s_g.Popup('Warning', 'Unusual Trend', title='Warning')
        elif i > 0 and neutral_counts[x[i - 1]] > good_counts[x[i - 1]] + bad_counts[x[i - 1]] \
                and neutral_counts[x[i - 1]] > 0 \
                and neutral_counts[x[i - 1]] + good_counts[x[i - 1]] + bad_counts[x[i - 1]] > 0:
            max_height = max(good_counts[x[i - 1]], bad_counts[x[i - 1]], neutral_counts[x[i - 1]])
            plt.annotate('Caring!', (x[i], max_height), ha='center', va='bottom',
                         color=(198 / 255, 119 / 255, 48 / 255),
                         alpha=1, fontsize=12)
            # s_g.Popup('Attention', 'Attention Needed', title='Attention')

    fig_name = f'{sth}_time.png'
    fig_path = fig_name
    fig.savefig(fig_path)
    plt.show()
    return fig_path


def count_analyze(sth, s_g, file_path='情感词分析.csv'):
    data = pd.read_csv(file_path, encoding='utf-8')
    Specify_data = data[data['itemName'] == sth]
    fig = plt.figure(figsize=(10, 6), dpi=500)
    sizes = Specify_data['Sentiment'].value_counts()
    labels = sizes.index
    palette = {'正面': (67 / 255, 255 / 255, 183 / 255), '中性': (255 / 255, 206 / 255, 70 / 255),
               '负面': (158 / 255, 41 / 255, 39 / 255)}
    plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90, colors=palette.values())
    plt.title('评论类型占比分布')

    plt.axis('equal')
    plt.legend(labels)
    fig_name = f'{sth}_count.png'
    fig_path = fig_name
    fig.savefig(fig_path)
    # 弹窗预警逻辑
    good_count = sizes.get('正面', 0)
    bad_count = sizes.get('负面', 0)
    neutral_count = sizes.get('中性', 0)
    total_count = good_count + bad_count + neutral_count

    if bad_count > good_count or bad_count > (good_count + neutral_count) * 0.6:
        sg.Popup('Warning', '该商品负面评论较多，需要注意！！', title='Warning')
    elif neutral_count > total_count * 0.6:
        sg.Popup('Attention', '该商品中立评论较多，需要考虑优化商品', title='Attention')
    plt.show()
    return fig_path



# #
# # 简单进行测试
# print("输入商品名称")
# name = input()
# path = month_analyze(name, sg)
# path2 = count_analyze(name, sg)

# dictionary = {'word': ['艹', '日你仙人', 'fuck', 'np', 'fw'],
#               'count': [25, 30, 35, 28, 32],
#               }
